#include <iostream>
#include <ctime>
#include <vector>

#include "LogWriter.h"


LogWriter::LogWriter(std::ostream& output, const std::string& header) :
	m_writeMutex(new std::mutex), m_output(output), m_header(header)
{}


void LogWriter::write_info(const std::string& msg) const
{
	write("INFO", msg);
}


void LogWriter::write_warning(const std::string& msg) const
{
	write("WARNING", msg);
}


void LogWriter::write_error(const std::string& msg) const
{
	write("ERROR", msg);
}


void LogWriter::write(const std::string& prefix, const std::string& msg) const
{
	std::unique_lock<std::mutex> lock(*m_writeMutex);
	time_t rawTime;
	struct tm* timeInfo;
	std::vector<char> timeBuffer(20);

	time (&rawTime);
	timeInfo = localtime(&rawTime);
	strftime(timeBuffer.data(), 20, "%H:%M:%S", timeInfo);

	m_output << "[" << timeBuffer.data() << " - " << prefix << "] ";
	
	if (!m_header.empty())
		m_output << m_header << " ~ ";

	m_output<< msg << "\n";
	
	m_output.flush();
}
